package com.cbwl.eoas.common.util.oss;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.cbwl.eoas.common.framework.exception.CustomException;



/**
 * 
 * <p>[描述信息：ossClinetUtil]</p>
 *
 * @author 虞云波 - yuyunbo@3856.cc
 * @version 1.0 Created on 2017年11月3日 上午11:07:25
 */
public class OSSClientUtil {
 
  Logger log = LoggerFactory.getLogger(OSSClientUtil.class);
  // endpoint以杭州为例，其它region请按实际情况填写
  private String endPoint = "oss-cn-beijing.aliyuncs.com";

  //private String accessKeyId = "LTAIKvR6EJThF8a9";
  private String accessKeyId = "LTAIlF9tDP8MBRme";
  
  //private String accessKeySecret = "2y9eMfOculXolnBZGOvHOgR7aUHPqR";
  private String accessKeySecret = "md7QXmwZARuJSMtvbQX8x56WH21muW";
  
  //空间
  private String bucketName = "eoas-file";
  //文件存储目录
  private String filedir = "eoas/";
 
  private OSSClient ossClient;
 
  public OSSClientUtil() {
    ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
  }
 
  /**
   * 
   * <p>初始化</p>
   * 
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:08:19
   */
  public void init() {
    ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
  }
 
  /**
   * 
   * <p>销毁</p>
   * 
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:08:31
   */
  public void destory() {
    ossClient.shutdown();
  }
 
  /**
   * 
   * <p>上传图片</p>
   * 
   * @param url url路径
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:08:41
   */
  public void uploadImg2Oss(String url) {
    File fileOnServer = new File(url);
    FileInputStream fin;
    try {
      fin = new FileInputStream(fileOnServer);
      String[] split = url.split("/");
      this.uploadFile2OSS(fin, split[split.length - 1],0);
    } catch (FileNotFoundException e) {
//      throw new ImgException("图片上传失败");
    }
  }
 
  /**
   * 
   * <p>web 端上传</p>
   * 
   * @param file
   * @return 文件的url路径
   * @author: 虞云波 - yuyunbo@3856.cc 
 * @throws CustomException 
   * @date: Created on 2017年11月3日 上午11:09:15
   */
  public String uploadImg2Oss(MultipartFile file) throws CustomException {
    if (file.getSize() > 1024 * 1024*10) {
      throw new CustomException("","上传图片大小不能超过1M！");
    }
    String originalFilename = file.getOriginalFilename();
    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    Random random = new Random();
    String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
    try {
      InputStream inputStream = file.getInputStream();
      this.uploadFile2OSS(inputStream, name,file.getSize());
      return getOssUrl(name);
    } catch (Exception e) {
      throw new CustomException("","图片上传失败");
    }
  }
 
  /**
   * 
   * <p>根据文件名称生成oss的访问路径</p>
   * 
   * @param fileUrl
   * @return
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:10:09
   */
  public String getOssUrl(String fileUrl) {
    if (!StringUtils.isEmpty(fileUrl)) {
      String[] split = fileUrl.split("/");
      return this.getUrl(this.filedir + split[split.length - 1]);
    }
    return null;
  }
 
  /**
   * 
   * <p>上传到OSS服务器  如果同名文件会覆盖服务器上的</p>
   * 
   * @param instream
   * @param fileName
   * @return
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:10:37
   */
  public String uploadFile2OSS(InputStream instream, String fileName,long fileSize) {
    String ret = "";
    try {
      //创建上传Object的Metadata 
      ObjectMetadata objectMetadata = new ObjectMetadata();
      objectMetadata.setContentLength(instream.available());
      objectMetadata.setCacheControl("no-cache");
      objectMetadata.setHeader("Pragma", "no-cache");
      objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
      objectMetadata.setContentDisposition("inline;filename=" + fileName);
      if(fileSize>0){
    	  objectMetadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");  
      }
      //上传文件
      PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
      ret = putResult.getETag();

    } catch (IOException e) {
      log.error(e.getMessage(), e);
    } finally {
      try {
        if (instream != null) {
          instream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return ret;
  }
 
  /**
   * 
   * <p>判断OSS服务文件上传时文件的contentType</p>
   * 
   * @param FilenameExtension
   * @return
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:10:52
   */
  public static String getcontentType(String FilenameExtension) {
    if (FilenameExtension.equalsIgnoreCase(".bmp")) {
      return "image/bmp";
    }
    if (FilenameExtension.equalsIgnoreCase(".gif")) {
      return "image/gif";
    }
    if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
        FilenameExtension.equalsIgnoreCase(".jpg") ||
        FilenameExtension.equalsIgnoreCase(".png")) {
      return "image/jpeg";
    }
    if (FilenameExtension.equalsIgnoreCase(".html")) {
      return "text/html";
    }
    if (FilenameExtension.equalsIgnoreCase(".txt")) {
      return "text/plain";
    }
    if (FilenameExtension.equalsIgnoreCase(".vsd")) {
      return "application/vnd.visio";
    }
    if (FilenameExtension.equalsIgnoreCase(".pptx") ||
        FilenameExtension.equalsIgnoreCase(".ppt")) {
      return "application/vnd.ms-powerpoint";
    }
    if (FilenameExtension.equalsIgnoreCase(".docx") ||
        FilenameExtension.equalsIgnoreCase(".doc")) {
      return "application/msword";
    }
    if (FilenameExtension.equalsIgnoreCase(".xml") || FilenameExtension.equalsIgnoreCase(".plist")) {
      return "text/xml";
    }
    if (FilenameExtension.equalsIgnoreCase(".apk")) {
        return "application/vnd.android.package-archive";
    }
   
    return "application/octet-stream";
  }
 
  /**
   * 
   * <p>获得url链接</p>
   * 
   * @param key
   * @return
   * @author: 虞云波 - yuyunbo@3856.cc 
   * @date: Created on 2017年11月3日 上午11:11:05
   */
  public String getUrl(String key) {
	  
    // 设置URL过期时间为10年  3600l* 1000*24*365*10
    Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
    // 生成URL
    URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
    if (url != null) {
      return url.toString().replaceFirst("http", "https");
    }
    return null;
  }
  
  
 
public String getEndPoint() {
	return endPoint;
}


public void setEndPoint(String endPoint) {
	this.endPoint = endPoint;
}


public String getAccessKeyId() {
	return accessKeyId;
}


public void setAccessKeyId(String accessKeyId) {
	this.accessKeyId = accessKeyId;
}


public String getAccessKeySecret() {
	return accessKeySecret;
}


public void setAccessKeySecret(String accessKeySecret) {
	this.accessKeySecret = accessKeySecret;
}

public String getBucketName() {
	return bucketName;
}


public void setBucketName(String bucketName) {
	this.bucketName = bucketName;
}

public String getFiledir() {
	return filedir;
}


public void setFiledir(String filedir) {
	this.filedir = filedir;
}


public OSSClient getOssClient() {
	return ossClient;
}


public void setOssClient(OSSClient ossClient) {
	this.ossClient = ossClient;
}

public static void main(String[] args) throws FileNotFoundException {
	 OSSClientUtil oss =  new OSSClientUtil();
	 
	 
	 
	String url = oss.getOssUrl("app_android.apk");
	File file = new File("d:\\apk\\app_android.apk");
     
	InputStream in = new FileInputStream(file);
	oss.uploadFile2OSS(in, "app_android.apk",0);
	 
	System.out.println(url);
	
	
	
	
}
  
  
}